package net.jarang.android.support.http;

import java.util.Map;

import net.jarang.support.StreamUtils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class DefaultHttpInvocator extends HttpInvocator {
	public DefaultHttpInvocator() {
		super(3000, 3000, "UTF-8");
	}

	public DefaultHttpInvocator(int connectionTimeout, int soTimeout, String encoding) {
		super(connectionTimeout, soTimeout, encoding);
	}
	
	public HttpResult get(String url, Map<String, Object> params, Map<String, String> headers) {
		HttpClient client = getHttpClient();
		GetMethod method = getMethod(url, params, headers);
		HttpResult httpResult = new HttpResult();
		
		try {
			long startTime = System.currentTimeMillis();
			client.executeMethod(method);

			httpResult.setResponseTime(System.currentTimeMillis() - startTime);
			httpResult.setStatusCode(method.getStatusCode());
			httpResult.setReturnValue(StreamUtils.streamToString(method.getResponseBodyAsStream(), getResponseEncoding(method)));
			httpResult.setCookies(client.getState().getCookies());
		} catch (Exception e) {
			throw new HttpCallException(e.getMessage(), e);
		} finally {
			releaseConnection(method);
		}
		return httpResult;
	}
	
	public HttpResult post(String url, Map<String, Object> params, Map<String, String> headers) {
		HttpClient client = getHttpClient();
		PostMethod method = postMethodForMultipart(url, params, headers);
		HttpResult httpResult = new HttpResult();

		try {
			long startTime = System.currentTimeMillis();
			client.executeMethod(method);

			httpResult.setResponseTime(System.currentTimeMillis() - startTime);
			httpResult.setStatusCode(method.getStatusCode());
			httpResult.setReturnValue(StreamUtils.streamToString(method.getResponseBodyAsStream(), getResponseEncoding(method)));
			httpResult.setCookies(client.getState().getCookies());
		} catch (Exception e) {
			throw new HttpCallException(e.getMessage(), e);
		} finally {
			releaseConnection(method);
		}
		return httpResult;
	}	
}
